#!/usr/bin/python3
# coding:utf-8            
#
# Copyright (C) 2024 - 2024 Husky， Inc. All Rights Reserved 
#
# @Project : {PROJECT_NAME}
# @Time    : 2024/7/13 21:29
# @Author  : yunluo
# @Email   : sp91@qq.com
# @File    : utils.py
# @IDE     : PyCharm
import json
import os
import time
from ctypes import windll

import requests
from loguru import logger
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

bad_list = []
tmp_dict = {}


def load_skip_list():
    """加载跳过列表"""
    if os.path.exists("skip_list.json"):
        try:
            with open("skip_list.json", "r", encoding="utf-8") as f:
                return set(json.load(f))
        except Exception:
            return set()
    return set()


def save_skip_list(skip_list):
    """保存跳过列表"""
    try:
        with open("skip_list.json", "w", encoding="utf-8") as f:
            json.dump(list(skip_list), f, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"保存跳过列表失败: {e}")


def add_to_skip_list(course_title):
    """添加课程到跳过列表"""
    skip_list = load_skip_list()
    skip_list.add(course_title)
    save_skip_list(skip_list)


def popup(title: str, msg: str, info_type: str):
    """
    弹窗提醒
    :param title:
    :param msg:
    :param info_type:
    :return:
    """
    msg_dict = {"error": 16, "question": 32, "warn": 48, "info": 64}
    return windll.user32.MessageBoxW(None, msg, title, msg_dict.get(info_type))


def switch_chinese(browser, lang_name: str = "简体中文"):
    """
    切换系统语言，默认是切换为简体中文
    :param browser:
    :param lang_name:需要切换的语言
    :return:
    """
    try:
        # 等待下拉按钮出现并点击它
        dropdown_button = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "yxt-dropdown-link"))
        )
        dropdown_button.click()

        # 定位并选择“简体中文”选项，可能不是太准确
        simplified_chinese_option = WebDriverWait(browser, 10).until(
            EC.visibility_of_element_located((By.XPATH, '//li[contains(text(),"{}")]'.format(lang_name)))
        )
        simplified_chinese_option.click()
    except Exception as e:
        logger.error(e)


def navigate_and_wait(browser, url: str, info_text: str, wait_time: int):
    """
    打开链接后等几秒
    :param browser: 浏览器对象
    :param url: 链接
    :param info_text:日志信息
    :param wait_time: 几秒钟
    :return:
    """
    try:
        browser.get(url)
        logger.info(info_text)
        # 使用智能等待而不是固定睡眠
        WebDriverWait(browser, wait_time).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "body")))
    except Exception as e:
        logger.error(e)


def click_element(element, info_text: str, wait_time: int):
    """
    点击元素并等待几秒
    :param element: 元素对象
    :param info_text: info 信息
    :param wait_time: 停止时间，数字
    :return:
    """
    try:
        element.click()
        logger.info(info_text)
        # 使用智能等待而不是固定睡眠
        time.sleep(wait_time)
        return True
    except Exception as e:
        logger.error(e)


def find_exsit_element(browser, selecter: str):
    """发现元素，不存在返回None"""
    try:
        return browser.find_element(By.CSS_SELECTOR, selecter)
    except NoSuchElementException:
        return None


def send_message(content, **kwargs):
    """Send Message."""
    baseurl = 'http://wxpusher.zjiecode.com/api'
    payload = {
        'appToken': kwargs.get('token'),
        'content': content,
        'summary': kwargs.get('summary'),
        'contentType': kwargs.get('content_type', 1),
        'topicIds': kwargs.get('topic_ids', []),
        'uids': kwargs.get('uids', []),
        'verifyPay': kwargs.get('verify'),
        'url': kwargs.get('url'),
    }
    url = f'{baseurl}/send/message'
    return requests.post(url, json=payload).json()